const util = require('../../utils/util.js');

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    tophead: {
      type: String
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    resources: [
      {id: 'seed', img: '/static/seed.png'},
      {id: 'fertilizer', img: '/static/fertilizer.png'},
      {id: 'water', img: '/static/water.png'},
      {id: 'coin',img: '/static/coin.png'},
    ],
  },
  //组件被附加到页面节点树时执行相应
  attached: function () {
    this.fetchResources();
  },

  methods: {

    /**
     * 在缓存更新金币数量
     */
    updateCoinAmount() {
      const updatedResources = this.data.resources.map(resource => {
        if (resource.id === 'coin') {
          const newAmount = resource.amount + 500;
          resource.amount = newAmount;
          this.updateCoin(newAmount);
          // 更新到缓存
          wx.setStorageSync('coinAmount', newAmount.toString());
        }
        return resource;
      });
      this.setData({
        resources: updatedResources
      });
    },

    /**
     * 在缓存和后端获取和更新各种资源数量
     */
    fetchResources: function () {

      // 设置资源数量到缓存
      const setResourceAmountToStorage = (key, amount) => {
        try {
          wx.setStorageSync(key, amount.toString());
        } catch (e) {
          console.error(`无法将 ${key} 添加到缓存:`, e);
        }
      };

      // 从本地缓存中获取资源数量
      const getResourceAmountFromStorage = (key) => {
        try {
          const value = wx.getStorageSync(key);
          if (value) {
            return parseInt(value, 10); // 返回整数类型的资源数量
          }
        } catch (e) {
          console.error(`无法从缓存获取 ${key}:`, e);
        }
        return null;
      };

      // 从后端获取资源数量
      const getResourceAmount = (url, key) => {
        const cachedAmount = getResourceAmountFromStorage(key);
        if (cachedAmount !== null) {
          return Promise.resolve(cachedAmount);
        }

        return util.request(getApp().globalData.requestUrl + url, 'GET', {})
          .then((response) => {
            const amount = response.data;
            setResourceAmountToStorage(key, amount);
            return amount;
          })
          .catch((error) => {
            console.error(`无法从 ${url} 获取资源数量:`, error);
            throw error; // 继续向下传递错误
          });
      };

      // 使用Promise.all同时请求所有资源的数量
      Promise.all([
        getResourceAmount('users/GetSeed', 'seedAmount'),
        getResourceAmount('users/GetWater', 'waterAmount'),
        getResourceAmount('users/GetFertilizer', 'fertilizerAmount'),
        getResourceAmount('users/GetCoin', 'coinAmount')
      ]).then(([seedAmount, waterAmount, fertilizerAmount, coinAmount]) => {

        // 更新资源列表
        const updatedResources = this.data.resources.map(resource => {
          switch (resource.id) {
            case 'seed':
              resource.amount = seedAmount;
              break;
            case 'water':
              resource.amount = waterAmount;
              break;
            case 'fertilizer':
              resource.amount = fertilizerAmount;
              break;
            case 'coin':
              resource.amount = coinAmount;
              break;
            default:
              break;
          }
          return resource;
        });
        this.setData({
          resources: updatedResources
        });
      }).catch((err) => {
        console.error('获取资源失败:', err);
      });
    },

    /**
     * 购买指定资源，更新到缓存和后端
     * @param {string} resourceId - 资源的ID
     * @param {number} price - 资源的价格
     */
    purchaseResource: function (resourceId, price) {
      const resources = this.data.resources;
      const resourceIndex = resources.findIndex(item => item.id === resourceId);
      const coinIndex = resources.findIndex(item => item.id === 'coin');
      if (resourceIndex !== -1 && coinIndex !== -1) {
        // 检查金币是否足够
        if (resources[coinIndex].amount >= price) {
          // 减少金币数量
          const newCoinAmount = resources[coinIndex].amount - price;
          resources[coinIndex].amount = newCoinAmount;
          wx.setStorageSync('coinAmount', newCoinAmount.toString());
          // 增加道具数量
          const newResourceAmount = resources[resourceIndex].amount + 1;
          resources[resourceIndex].amount = newResourceAmount;
          wx.setStorageSync(resourceId + 'Amount', newResourceAmount.toString());
          this.setData({
            resources: resources
          });
          this.updateCoin(newCoinAmount);
          this.updateResource(resourceId, newResourceAmount);
        } else {
          wx.showToast({
            title: '金币不足',
            icon: 'none'
          });
        }
      }
    },

    /**
     * 更新指定类型的资源数量到后端和缓存
     * @param {string} type - 资源类型 
     * @param {number} newData - 新的资源数量
     */
    updateResource: function (type, newData) {
      let url;
      let storageKey;
      // 根据资源类型选择对应的URL和缓存键名
      switch (type) {
        case 'seed':
          url = getApp().globalData.requestUrl + 'users/UpdateSeed';
          storageKey = 'seedAmount';
          break;
        case 'fertilizer':
          url = getApp().globalData.requestUrl + 'users/UpdateFertilizer';
          storageKey = 'fertilizerAmount';
          break;
        case 'water':
          url = getApp().globalData.requestUrl + 'users/UpdateWater';
          storageKey = 'waterAmount';
          break;
        default:
          console.error('不支持的类型:', type);
          return;
      }
      util.request(url, 'POST', {
          newData: newData
        })
        .then((res) => {
          if (res.code === 200) {
            console.log('数据更新成功');
            wx.setStorageSync(storageKey, newData.toString());
          } else {
            console.error('更新数据失败:', res.message);
          }
        })
        .catch((error) => {
          console.error('数据更新失败:', error);
        });
    },

    /**
     * 更新金币数量到后端和缓存
     * @param {number} newCoin - 新的金币数量
     */
    updateCoin: function (newCoin) {
      util.request(getApp().globalData.requestUrl + 'users/UpdateCoin', 'POST', {
          newData: newCoin
        })
        .then((res) => {
          if (res.code === 200) {
            console.log('金币更新成功');
            // 更新本地缓存
            wx.setStorageSync('coinAmount', newCoin.toString());
          } else {
            console.error('更新金币失败:', res.message);
          }
        })
        .catch((error) => {
          console.error('金币更新失败:', error);
        });
    },

    /**
     * 使用指定资源，更新到缓存和后端
     * @param {string} resourceId - 资源的ID
     * @returns {boolean} 是否使用成功
     */
    useWay: function (resourceId) {
      const resources = this.data.resources;
      const resourceIndex = resources.findIndex(item => item.id === resourceId);
      if (resourceIndex !== -1) {
        // 检查道具是否足够
        if (resources[resourceIndex].amount > 0) {
          // 减少道具数量
          const newAmount = resources[resourceIndex].amount - 1;
          resources[resourceIndex].amount = newAmount;
          this.setData({
            resources: resources
          });
          this.updateResource(resources[resourceIndex].id, newAmount);
          const storageKey = `resource_${resources[resourceIndex].id}`;
          wx.setStorageSync(storageKey, newAmount.toString());
          return true;
        } else {
          wx.showToast({
            title: '道具不足',
            icon: 'none'
          });
          return false;
        }
      }
      return false;
    },
  }
});